package com.chenyue.cm.live.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.live.domain.JdLive;
import com.chenyue.cm.live.domain.JdLiveExample;
import com.chenyue.cm.live.service.JdLiveService;
import com.chenyue.cm.live.vo.LiveUser;
import com.chenyue.cm.live.vo.SetLiveUser;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.user.vo.CheckMobileUserVo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenyue-cm
 * @date 2021-07-20
 */
@RestController
@RequestMapping("/jdLive")
public class JdLiveController {

    private final JdLiveService jdLiveService;

    private final JdAppUserService appUserService;

    public JdLiveController(JdLiveService jdLiveService, JdAppUserService appUserService) {
        this.jdLiveService = jdLiveService;
        this.appUserService = appUserService;
    }

    @RequestMapping("/getList")
    public Success getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JdLive> result = jdLiveService.getPageBean(pageInfo, JdLive.class);
        return Success.success(result);
    }

    @RequestMapping("/getAllList")
    public Success getAllList(HttpServletRequest request) {
        List<JdLive> list = jdLiveService.list(new QueryWrapper<JdLive>()
                .lambda()
                .eq(JdLive::getParentUser, 0)
        );
        List<Integer> userIds = list.stream().distinct().map(JdLive::getUserId).collect(Collectors.toList());
        List<JdAppUser> jdAppUsers = null;
        if(userIds != null && userIds.size()>0){
            jdAppUsers = appUserService.listByIds(userIds);
        }
        
        return Success.success(jdAppUsers);
    }

    @RequestMapping("/getLiveList")
    public Success getLiveList(HttpServletRequest request) {
        String liveId = request.getParameter("liveId");
        QueryWrapper<JdLive> wrapper = new QueryWrapper<>();
        wrapper.eq("id", liveId);
        List<JdLive> list = jdLiveService.list(wrapper);
        return Success.success(list);
    }

    /**
     * @param vo 插入实体
     * @return Success
     */
    @Log
    @RequestMapping("/save")
    public Success save(JdLive vo) {
        boolean success = jdLiveService.save(vo);
        return success ? Success.success() : Success.error();
    }

    @Log
    @RequestMapping("/saveLiveUser")
    public Success saveLiveUser(SetLiveUser vo) {
        List<SetLiveUser> liveUserList = new ArrayList<>();
        liveUserList.add(vo);
        return jdLiveService.setLiveUser(liveUserList, 0);
//        //从主播列表中 给主播分配身份
//        JdLive live = jdLiveService.getOne(new QueryWrapper<JdLive>()
//                .lambda()
//                .eq(JdLive::getUserId, vo.getNumber())
//                .last("limit 1")
//        );
//        live.setParentUser("0");
//        live.setRole(vo.getRole());
//        int success = jdLiveService.updateByPrimaryKey(live);
//        return success > 0 ? Success.success() : Success.error();
    }

    @PostMapping("/setLiveUserCheck")
    @ApiOperation(value = "第三方机构 设置赛事主播前 每个手机号需要单独校验", notes = "第三方机构 设置赛事主播每个手机号需要单独校验")
    public Success<String> setLiveUserCheck(SetLiveUser liveUserList) {
        JdAppUser appUser;
        if (11 != liveUserList.getNumber().length()) {
            appUser = appUserService.getOne(new QueryWrapper<JdAppUser>().lambda()
                    .eq(JdAppUser::getUserNum, liveUserList.getNumber())
                    .last(" limit 1")
            );
            if (null == appUser) {
                return Success.error("无此ID");
            }
        } else {
            List<CheckMobileUserVo> voList = new ArrayList<>();
            CheckMobileUserVo vo = new CheckMobileUserVo();
            vo.setMobile(liveUserList.getNumber());
            voList.add(vo);
            //校验手机号，没有就注册
            appUserService.checkMobileUser(voList);
            appUser = appUserService.getOne(new QueryWrapper<JdAppUser>().lambda()
                    .eq(JdAppUser::getMobile, liveUserList.getNumber())
                    .last(" limit 1")
            );
        }
        JdLive live = jdLiveService.lambdaQuery().eq(JdLive::getUserId, appUser.getId()).last("limit 1").one();
        if (live != null) {
            return Success.error("用户" + liveUserList.getNumber() + "已经是主播");
        }
        return Success.success();
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return Success
     */
    @Log
    @RequestMapping("/edit")
    public Success edit(JdLive vo, HttpServletRequest request) {
        String id = request.getParameter("liveId");
        if (StringUtils.isNotBlank(id)) {
            vo.setId(Integer.parseInt(id));
            int success = jdLiveService.getBaseMapper().updateById(vo);
            return success > 0 ? Success.success() : Success.error();
        } else {
            return Success.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return Success
     */
    @Log
    @RequestMapping("/delete/{id}")
    public Success deleteByPrimaryKey(@PathVariable("id") Integer id) {
        JdLiveExample aExample = new JdLiveExample();
        aExample.createCriteria().andIdEqualTo(id);
        int success = jdLiveService.deleteByExample(aExample);
        return success > 0 ? Success.success() : Success.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return Success
     */
    @Log
    @RequestMapping("/delete")
    public Success delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            int success = jdLiveService.deleteByPrimaryKey(idString);
            if (success == 0) {
                return Success.error();
            }
        }
        return Success.success();
    }

    @Log
    @RequestMapping("/getLiveUserList")
    public Success getLiveUserList(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        Pageable pageInfo = RequestUtil.getPageable(request);
        Page<List<LiveUser>> liveUserList = jdLiveService.getLiveUserList(userId, pageInfo.getPageIndex(), pageInfo.getPageSize(),pageInfo);
        return Success.success(liveUserList);
    }

    @Log
    @RequestMapping("/getJdLiveUserList")
    public Success getJdLiveUserList(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        List<LiveUser> liveUserList = jdLiveService.getJdLiveUserList(userId);
        return Success.success(liveUserList);
    }


}
